package com.taxshare.seller.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.constant.ResultConstant;
import com.taxshare.seller.entity.GoodsManageEntity;
import com.taxshare.seller.entity.ProductCodeEntity;
import com.taxshare.seller.entity.excel.GoodsManageExcelEntity;
import com.taxshare.seller.mapper.GoodsManageMapper;
import com.taxshare.seller.view.dto.ExcelDTO;
import com.taxshare.seller.view.dto.GoodsManageDTO;
import com.taxshare.seller.view.dto.PjspbmDTO;
import com.taxshare.seller.view.dto.TaxComplilationDTO;
import com.taxshare.tools.util.ExcelUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;

/**
 * @author YANG
 * @date 2021/3/16
 * @Description:商品管理
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class GoodsManageService extends ServiceImpl<GoodsManageMapper, GoodsManageEntity> {

    @Autowired
    ProductCodeService productCodeService;

    @Autowired
    CommService commService;

    /**
     * 商品管理【商品信息新增】
     *
     * @return
     */
    public Response goodsManageAdd(GoodsManageDTO goodsManageDto) {
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("goods_code", goodsManageDto.getGoodsCode());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error("SEL_011");
        }
        GoodsManageEntity goodsManageEntity = DozerBeanUtil.map(goodsManageDto, GoodsManageEntity.class);
        goodsManageEntity.setUuid(UUIDUitl.UUID32(false));
        goodsManageEntity.setMark("1");
        this.save(goodsManageEntity);
        return Response.success();
    }

    /**
     * 商品管理【商品信息删除】
     *
     * @return
     */
    public Response goodsManageRemove(List<String> ids) {
        this.removeByIds(ids);
        return Response.success();
    }

    /**
     * 商品管理【商品信息编辑】
     *
     * @param goodsManageDto
     * @return
     */
    public Response goodsManageEdit(GoodsManageDTO goodsManageDto) {
        //String uuid = invoiceExistsSubmit(goodsManageDto).getUuid();
        UpdateWrapper<GoodsManageEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("uuid", goodsManageDto.getUuid())
                .set("goods_code", goodsManageDto.getGoodsCode())
                .set("goods_name", goodsManageDto.getGoodsName())
                .set("tax_rate", goodsManageDto.getTaxRate())
                .set("model", goodsManageDto.getModel())
                .set("unit", goodsManageDto.getUnit())
                .set("tax_code", goodsManageDto.getTaxCode())
                .set("tax_name", goodsManageDto.getTaxName())
                .set("duty_free_type", goodsManageDto.getDutyFreeType())
                .set("preferential_mark", goodsManageDto.getPreferentialMark())
                .set("preferential_name", goodsManageDto.getPreferentialName())
                .set("seller_name", goodsManageDto.getSellerName())
                .set("seller_tax_no", goodsManageDto.getSellerTaxNo())
                .set("company_code", goodsManageDto.getCompanyCode());
        GoodsManageEntity entity = new GoodsManageEntity();
        int result = baseMapper.update(entity, updateWrapper);
        if (result != 1) {
            return Response.error(ResultConstant.RET_P0013CODE, ResultConstant.RET_P0013_MSG);
        }
        return Response.success();
    }

    /**
     * 发票提交判断
     *
     * @param dto
     * @return
     */
    private GoodsManageEntity invoiceExistsSubmit(GoodsManageDTO dto) {
        String goodsCode = dto.getGoodsCode();
        String goodsName = dto.getGoodsName();
        GoodsManageEntity goodsManageEntity = baseMapper.query(goodsCode, goodsName);
        return goodsManageEntity;
    }

    /**
     * 商品管理【商品信息查询】
     *
     * @param query
     * @return
     */
    public Response goodsManageQuery(PageRequest<TaxComplilationDTO> query) {
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper();
        TaxComplilationDTO taxComplilationDTO = query.getInfo();

        if (StrUtil.isNotBlank(taxComplilationDTO.getGoodsCode())) {
            queryWrapper.eq("goods_code", taxComplilationDTO.getGoodsCode());
        }
        if (StrUtil.isNotBlank(taxComplilationDTO.getGoodsName())) {
            queryWrapper.like("goods_name", taxComplilationDTO.getGoodsName());
        }
        if (StrUtil.isNotBlank(taxComplilationDTO.getTaxRate())) {
            queryWrapper.eq("tax_rate", taxComplilationDTO.getTaxRate());
        }
        if (StrUtil.isNotBlank(taxComplilationDTO.getTaxName())) {
            queryWrapper.like("tax_name", taxComplilationDTO.getTaxName());
        }
        if (StrUtil.isNotBlank(taxComplilationDTO.getTaxCode())) {
            queryWrapper.eq("tax_code", taxComplilationDTO.getTaxCode());
        }
        if (StrUtil.isNotBlank(taxComplilationDTO.getSellerTaxNo())) {
            queryWrapper.eq("seller_tax_no", taxComplilationDTO.getSellerTaxNo());//销方税号
        }/*else {
            List<String> taxNos = commService.getTaxNumbers();
            queryWrapper.in("seller_tax_no", taxNos);//销方税号
        }*/
        queryWrapper.eq("mark", "1")
                .orderByDesc("create_time");
        IPage<GoodsManageEntity> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), GoodsManageEntity.class);
        return Response.success(result);
    }

    /**
     * 获取商品编码
     *
     * @param pjspbmDTO
     * @return
     */
    public Response getProductCode(PjspbmDTO pjspbmDTO) {
        QueryWrapper<ProductCodeEntity> queryWrapper = new QueryWrapper<>();
        List zTreeData = new ArrayList();
        String pid = "";
        if (StrUtil.isEmpty(pjspbmDTO.getPid())) {
            pid = "0";
        } else {
            pid = pjspbmDTO.getPid();
        }
        queryWrapper.eq("pid", pid).eq("kyzt", "Y");
        List<ProductCodeEntity> productCodeEntities = productCodeService.list(queryWrapper);
        NumberFormat nf = NumberFormat.getPercentInstance();
        for (int i = 0; i < productCodeEntities.size(); i++) {
            Map<String, Object> node = new HashMap();
            ProductCodeEntity productCodeEntity = productCodeEntities.get(i);
            node.put("id", productCodeEntity.getSpbm());
            node.put("name", productCodeEntity.getSpmc());
            node.put("sm", productCodeEntity.getSm());
            try {
                node.put("sl", StrUtil.isEmpty(productCodeEntity.getZzssl()) ? "0" : nf.parse(productCodeEntity.getZzssl()).toString());
            } catch (ParseException e) {
                node.put("sl", "0");
            }
            if ("Y".equals(productCodeEntity.getHzx())) {
                node.put("isChild", false);
            } else {
                node.put("isChild", true);
            }
            zTreeData.add(node);
        }
        return Response.success(zTreeData);
    }

    /**
     * 商品管理信息【商品管理信息导入】
     *
     * @param excelFile
     */
    public Response GoodsManageImport(MultipartFile excelFile) {
        List<GoodsManageDTO> excelDTOList;
        try {
            excelDTOList = ExcelUtil.readExcel(excelFile.getInputStream(), new GoodsManageDTO(), GoodsManageDTO.class);
            //循环校验
            for (GoodsManageDTO dto : excelDTOList) {
                String taxRate = dto.getTaxRate();
                //税率校验
                if(StrUtil.isNotBlank(taxRate)){
                    String[] strings = dto.getTaxRate().split("%");
                    if(strings.length >= 2){
                        return Response.error(ResultConstant.RET_P0018CODE, "商品名称为：" + dto.getGoodsName() + "的商品税率错误，请检查后重试");
                    }else{
                        int index = taxRate.indexOf("%");
                        if(index != -1){
                            taxRate  = Double.valueOf(strings[0])/100+"";
                        }else{
                            taxRate  = strings[0];
                        }
                        dto.setTaxRate(taxRate);
                        if(Double.valueOf(taxRate) > 1){
                            return Response.error(ResultConstant.RET_P0018CODE, "商品名称为：" + dto.getGoodsName() + "的商品税率错误，请检查后重试");
                        }
                    }
                }
                String dutyFreeType = dto.getDutyFreeType();
                String preferentialMark = dto.getPreferentialMark();
                String preferentialName = dto.getPreferentialName();
                //必填项校验
                if (StrUtil.isEmpty(taxRate) || StrUtil.isEmpty(dto.getTaxCode()) || StrUtil.isEmpty(dto.getTaxName()) || StrUtil.isEmpty(dto.getGoodsCode()) || StrUtil.isEmpty(dto.getGoodsName()) || StrUtil.isEmpty(preferentialMark)) {
                    return Response.error(ResultConstant.RET_P0018CODE, ResultConstant.RET_P0018_MSG);
                }
                //优惠政策 是/否 填写规范校验
                if (favouredPolicyJudge(preferentialMark)) {
                    return Response.error(ResultConstant.RET_P0014CODE, ResultConstant.RET_P0014_MSG);
                }
                //优惠类型填写规格校验
                if (favouredPolicyNameJudge(preferentialName)) {
                    return Response.error(ResultConstant.RET_P0015CODE, ResultConstant.RET_P0015_MSG);
                }
                ;
                //税率填写规格校验
                if (rateJudge(taxRate)) {
                    return Response.error(ResultConstant.RET_P0016CODE, ResultConstant.RET_P0016_MSG);
                }
                ;
                //免税类型填写规格校验
                if (rateNameJudge(taxRate)) {
                    return Response.error(ResultConstant.RET_P0020CODE, ResultConstant.RET_P0020_MSG);
                }
                //优惠政策是否和优惠类型的逻辑校验
                Response response;
                int i = preferentialJudge(preferentialMark, preferentialName);
                response =
                        i == 1 ? Response.error(ResultConstant.RET_P0021CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0021_MSG) :
                                (i == 2 ? Response.error(ResultConstant.RET_P0022CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0022_MSG) :
                                        (i == 3 ? Response.error(ResultConstant.RET_P0015CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0015_MSG) : Response.success()));
                if (!response.SUCCESS.equals(response.getCode())) {
                    return response;
                }
                //0税率和免税类型逻辑校验
                int t = taxRateJudge(taxRate, dutyFreeType);
                response =
                        t == 1 ? Response.error(ResultConstant.RET_P0017CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0017_MSG) :
                                (t == 2 ? Response.error(ResultConstant.RET_P0019CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0019_MSG) :
                                        (t == 3 ? Response.error(ResultConstant.RET_P0020CODE, "项目编码：" + dto.getSellerTaxNo() + "，商品编码：" + dto.getGoodsCode() + "的税编信息，" + ResultConstant.RET_P0020_MSG) : Response.success()));
                if (!response.SUCCESS.equals(response.getCode())) {
                    return response;
                }
                //优惠政策标识 转换
                dto.setPreferentialMark(mkMap.get(preferentialMark).toString());
                GoodsManageEntity goodsManageEntity = DozerBeanUtil.map(dto, GoodsManageEntity.class);
                GoodsManageEntity existsEntity = invoiceExistsSubmit(dto);
                if (existsEntity == null) {
                    //添加 税编信息
                    goodsManageEntity.setUuid(UUIDUitl.UUID32(false));
                    goodsManageEntity.setMark("1");
                    goodsManageEntity.setTaxRateMark(goodsManageEntity.getDutyFreeType());
                    this.save(goodsManageEntity);
                } else {
                    //更新 税编信息
                    goodsManageEntity.setUuid(existsEntity.getUuid());
                    goodsManageEntity.setUpdateTime(new Date());
                    this.updateById(goodsManageEntity);
                }

            }
        } catch (IOException e) {
            log.error("上传文件异常：", e);
            return Response.error(ResultConstant.RET_P0011_CODE, ResultConstant.RET_P0011_MSG);
        }
        return Response.success();
    }

    /**
     * 商品管理【商品信息导出】
     *
     * @param response
     * @return
     */
    public void exportGoodsManageExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper<>();
        String sellerTaxNo = request.getParameter("sellerTaxNo");
        String goodsCode = request.getParameter("goodsCode");
        String goodsName = request.getParameter("goodsName");
        String taxName = request.getParameter("taxName");
        String taxCode = request.getParameter("taxCode");
        String taxRateNum = request.getParameter("taxRate");
        if (StrUtil.isNotBlank(sellerTaxNo)){
            queryWrapper.eq("seller_tax_no",sellerTaxNo);
        }/*else {
            List<String> taxNumbers = commService.getTaxNumbers();
            queryWrapper.in("seller_tax_no",taxNumbers);
        }*/
        if (StrUtil.isNotBlank(goodsCode)){
            queryWrapper.eq("goods_code",goodsCode);
        }
        if (StrUtil.isNotBlank(goodsName)){
            queryWrapper.eq("goods_name",goodsName);
        }
        if (StrUtil.isNotBlank(taxName)){
            queryWrapper.eq("tax_name",taxName);
        }
        if (StrUtil.isNotBlank(taxCode)){
            queryWrapper.eq("tax_code",taxCode);
        }
        if (StrUtil.isNotBlank(taxRateNum)){
            queryWrapper.eq("tax_rate",taxRateNum);
        }
        List<GoodsManageExcelEntity> goodsManageExcelEntities = baseMapper.queryGoodsManage(queryWrapper);
        for (int i = 0; i < goodsManageExcelEntities.size(); i++) {
            String dutyFreeType = goodsManageExcelEntities.get(i).getDutyFreeType();
            String taxRate = goodsManageExcelEntities.get(i).getTaxRate();
            String preferentialMark = goodsManageExcelEntities.get(i).getPreferentialMark();
            /*if (taxRate != null && !"".equals(taxRate)) {
                goodsManageExcelEntities.get(i).setTaxRate(DecimalFormat(taxRate));
            }*/
            if ("1".equals(dutyFreeType)) {
                goodsManageExcelEntities.get(i).setDutyFreeType("出口免税和其他免税优惠政策(免税)");
            }
            if ("2".equals(dutyFreeType)) {
                goodsManageExcelEntities.get(i).setDutyFreeType("不征增值税(不征税)");
            }
            if ("3".equals(dutyFreeType)) {
                goodsManageExcelEntities.get(i).setDutyFreeType("普通零税率(0%)");
            } else if ("".equals(dutyFreeType)) {
                goodsManageExcelEntities.get(i).setDutyFreeType("");
            }

            if ("0".equals(preferentialMark)) {
                goodsManageExcelEntities.get(i).setPreferentialMark("没有优惠政策");
            } else if ("1".equals(preferentialMark)) {
                goodsManageExcelEntities.get(i).setPreferentialMark("有优惠政策");
            }
        }
        List<String> cols = ExcelDTO.goodsManageCols;

        HashMap<String, String> map = new HashMap<>();
        map.put("goodsCode", "商品编码");
        map.put("goodsName", "商品名称");
        map.put("taxRate", "税率");
        map.put("model", "规格型号");
        map.put("unit", "计量单位");
        map.put("taxCode", "税收分类编码");
        map.put("taxName", "税收分类名称");
        map.put("dutyFreeType", "免税类型");
        map.put("preferentialMark", "是否享受优惠政策");
        map.put("preferentialName", "优惠政策名称");
        ExcelUtil.exportExcel(response, cols, map, goodsManageExcelEntities, "商品管理信息");
    }

    /**
     * 税率判断
     */
    public boolean rateJudge(String rate) {
        //List<String> rates = Arrays.asList("0", "0.01", "0.03", "0.05", "0.06", "0.09", "0.10", "0.11", "0.13", "0.16", "0.17");
        List<String> rates = Arrays.asList("0%", "1%", "3%", "5%", "6%", "9%", "10%", "11%", "13%", "16%", "17%");
        System.out.println("============"+rates.contains(rate));
        return rates.contains(rate);
    }

    /**
     * 免税类型判断
     */
    public boolean rateNameJudge(String rateName) {
        List<String> rates = Arrays.asList("1", "2", "3");
        return rates.contains(rateName);
    }

    /**
     * 优惠政策判断
     */
    public boolean favouredPolicyJudge(String rate) {
        List<String> fp = Arrays.asList("0", "1");
        return fp.contains(rate);
    }

    /**
     * 优惠政策名称判断
     */
    public boolean favouredPolicyNameJudge(String favouredPolicyName) {
        List<String> PolicyNames = Arrays.asList("00001", "00002", "00003", "00004", "00005", "00006", "00007", "00008", "00009", "00010", "00011", "00012", "免税", "00014", "00015", "00016");
        return PolicyNames.contains(favouredPolicyName);
    }

    public final static Map mkMap = new HashMap();

    static {
        mkMap.put("是", "1");
        mkMap.put("否", "0");
    }

    public final static Map mslxMap = new HashMap();

    static {
        mslxMap.put("1", "出口免税和其他免税优惠政策(免税)");
        mslxMap.put("2", "不征增值税(不征税)");
        mslxMap.put("3", "普通零税率(0%)");
    }

    //税率 格式转化
    public static String DecimalFormat(String s) {
        double a = Double.parseDouble(s);
        DecimalFormat df = new DecimalFormat("0%");
        String r = df.format(a);
        return r;
    }

    public int preferentialJudge(String preferentialMark, String preferentialName) {
        if ("0".equals(preferentialMark) && !StrUtil.isEmpty(preferentialName)) {
            return 1;
        }
        if ("1".equals(preferentialMark) && preferentialName.isEmpty()) {
            return 2;
        }
        return 0;
    }

    public int taxRateJudge(String taxRate, String dutyFreeType) {
        if ("0".equals(taxRate) && !StrUtil.isEmpty(dutyFreeType)) {
            if (mslxMap.get(dutyFreeType) == null) {
                return 1;
            }
        }
        if ("0".equals(taxRate) && StrUtil.isEmpty(dutyFreeType)) {
            return 2;
        }
        if (!"0".equals(taxRate) && !StrUtil.isEmpty(dutyFreeType)) {
            return 3;
        }
        return 0;
    }

    /**
     * 商品查询
     * @param
     * @return
     */
    public Response getGoods(TaxComplilationDTO dto) {
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(dto.getSellerTaxNo())) {
            queryWrapper.eq("seller_tax_no", dto.getSellerTaxNo());//销方税号
        }else {
            List<String> taxNos = commService.getTaxNumbers();
            queryWrapper.in("seller_tax_no", taxNos);//销方税号
        }
        queryWrapper.eq("mark",1);
        return Response.success(this.list(queryWrapper));
    }

    /**
     * 商品管理查询全部Post
     * @param
     * @return
     */
    public Response queryAllPost(TaxComplilationDTO query) {
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(query.getGoodsCode())) {
            queryWrapper.eq("goods_code", query.getGoodsCode());
        }
        if (StrUtil.isNotBlank(query.getGoodsName())) {
            queryWrapper.like("goods_name", query.getGoodsName());
        }
        if (StrUtil.isNotBlank(query.getTaxCode())) {
            queryWrapper.eq("tax_code", query.getTaxCode());
        }
        if (StrUtil.isNotBlank(query.getTaxRate())) {
            queryWrapper.eq("tax_rate", query.getTaxRate());
        }
        if (StrUtil.isNotBlank(query.getSellerTaxNo())) {
            queryWrapper.eq("seller_tax_no", query.getSellerTaxNo());//销方税号
        }else {
            List<String> taxNos = commService.getTaxNumbers();
            queryWrapper.in("seller_tax_no", taxNos);//销方税号
        }
        queryWrapper.eq("mark", "1").orderByDesc("create_time");
        List<GoodsManageEntity> oldList = this.list(queryWrapper);
        List<GoodsManageEntity> hasList = new ArrayList<>();
        List<GoodsManageEntity> notHasList = new ArrayList<>();
        List<GoodsManageEntity> newList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(query.getUuidList())){
            for(int i=0;i<oldList.size();i++){
                if(query.getUuidList().contains(oldList.get(i).getUuid())){
                    hasList.add(oldList.get(i));
                }else {
                    notHasList.add(oldList.get(i));
                }
            }
            newList.addAll(hasList);
            newList.addAll(notHasList);
        }else {
            newList.addAll(oldList);
        }
        return Response.success(newList);
    }

}